//
//  HMAddCartWithSize.m
//  HMMarket
//
//  Created by maimaigo3 on 2017/5/27.
//  Copyright © 2017年 homai. All rights reserved.
//


#define kHeight 49
#import "HMAddCartWithSize.h"
#import "HMProductSizeTableViewCell.h"
#import "HMChangeNumberTableViewCell.h"
#import "SearchModel.h"
#import "HMLoginController.h"
@interface HMAddCartWithSize ()<UITableViewDelegate, UITableViewDataSource, HMChangeNumberTableViewCellDelegate, HMProductSizeTableViewCellDelegate>

NS_STRONG NSArray *sizeArry;

NS_ASSIGN BOOL is_specialPrice;

NS_STRONG UITableView *myTableView;

NS_STRONG UIView  *backView;

NS_STRONG UIButton *footBtn;

NS_STRONG SearchModel *search;

NS_STRONG NSMutableDictionary *keepSizeDict;

NS_COPY   NSString *textNumber;
@end

@implementation HMAddCartWithSize

- (instancetype)init {
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, KWidthSCREEN, KHeightSCREEN);
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
        
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, KHeightSCREEN - kHeight * 3, KWidthSCREEN, kHeight * 3)];
        _backView.frame = CGRectMake(0, KHeightSCREEN - kHeight * 3, KWidthSCREEN, kHeight * 3);
        _backView.backgroundColor = [UIColor whiteColor];
        
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidthSCREEN, kHeight * 2) style:UITableViewStylePlain];
        self.myTableView.scrollEnabled = NO;
        self.myTableView.delegate = self;
        self.myTableView.dataSource = self;
        [_backView addSubview:self.myTableView];
        
        _footBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_footBtn setTitle:@"确认" forState:UIControlStateNormal];
        [_footBtn addTarget:self action:@selector(completeSelect) forControlEvents:UIControlEventTouchUpInside];
        _footBtn.frame = CGRectMake(0, _backView.frame.size.height - kHeight, KWidthSCREEN, kHeight);
        [_footBtn setBackgroundColor:kMainColor];
        [_backView addSubview:_footBtn];
        
        _textNumber = @"1";
        
        [self addSubview:_backView];
    }
    return self;
}

- (void)setLastPro:(HMLastPro *)lastPro {
    _lastPro = lastPro;
    [self keepBaseSizeArray];
    self.myTableView.frame = CGRectMake(0, 0, KWidthSCREEN, kHeight * (lastPro.attr.count + 1));
    _backView.frame = CGRectMake(0, KHeightSCREEN - kHeight * (lastPro.attr.count + 2), KWidthSCREEN, kHeight * (lastPro.attr.count + 2));
    _footBtn.frame = CGRectMake(0, _backView.frame.size.height - kHeight, KWidthSCREEN, kHeight);
    [self.myTableView reloadData];
//    [self getData:_lastPro.id];
}

//- (void)getData:(NSString *)idString{
//    [HttpBaseTool get:kGoodsDes params:@{@"item_id":idString} success:^(id responseObj) {
//        _search = [SearchModel mj_objectWithKeyValues:responseObj[@"data"]];
//        
//        _backView.frame = CGRectMake(0, KHeightSCREEN - kHeight * (_search.attr.count + 2), KWidthSCREEN, kHeight * (_search.attr.count + 2));
//        self.myTableView.frame = CGRectMake(0, 0, KWidthSCREEN, kHeight * (_search.attr.count + 1));
//        _footBtn.frame = CGRectMake(0, _backView.frame.size.height - kHeight, KWidthSCREEN, kHeight);
//        [_myTableView reloadData];
//        
//        [self keepBaseSizeArray];
//    } failure:^(NSError *error) {
//        
//    }];
//}

- (void)keepBaseSizeArray {
//    _dataArray = [_lastPro.attr[i][@"attr_value"] componentsSeparatedByString:@","];
    
    _keepSizeDict = [NSMutableDictionary dictionary];
    for (int i = 0; i < _lastPro.attr.count; i++) {
        NSDictionary *stringDict = _lastPro.attr[i];
        NSArray *dataArr = [stringDict[@"attr_value"] componentsSeparatedByString:@","];
        [self.keepSizeDict setObject:[dataArr firstObject] forKey:stringDict[@"attr_name"]];
    }
}

- (void)dismiss {
    [self removeFromSuperview];
}

- (void)show {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
}

- (void)completeSelect {
    [self endEditing:YES];
    // 先判断有无存储账号信息
    if ([MGAccountTool getUsername] == nil) { // 之前没有登录成功
        [HMHUDManager showHUDWithText:@"未登录"];
        if ([_delegate respondsToSelector:@selector(noLogin)]) {
            [_delegate noLogin];
        }
    } else {
        NSArray *keyArray = [self.keepSizeDict allKeys];
        NSString *item_attr = @"";
        for (int i = 0; i < keyArray.count; i++) {
            if (i == 0) {
                item_attr = [NSString stringWithFormat:@"%@:%@",keyArray[i] , self.keepSizeDict[keyArray[i]]];
            } else {
                NSString *attr = [NSString stringWithFormat:@"%@:%@",keyArray[i] , self.keepSizeDict[keyArray[i]]];
                item_attr = [NSString stringWithFormat:@"%@,%@", item_attr, attr];
            }
        }
        
        NSDictionary *parm = @{@"user_tel":[MGAccountTool getTel], @"item_id":_lastPro.id, @"item_number":_textNumber, @"item_price":_lastPro.item_price, @"item_attr":item_attr};
        
        [HttpBaseTool post:kAddCart params:parm success:^(id responseObj) {
            if ([responseObj[@"code"] integerValue] == 200) {
                LoginSuccess;
                [HMHUDManager showHUDWithText:@"添加成功"];
                if ([_delegate respondsToSelector:@selector(getSelectSize:number:)]) {
                    [_delegate getSelectSize:[_keepSizeDict allValues] number:_textNumber];
                }
            } else {
                [HMHUDManager showHUDWithText:responseObj[@"msg"]];
            }
        } failure:^(NSError *error) {
            
        }];
    }
    
    
//    NSMutableArray *attr_id = [NSMutableArray array];
//    NSArray *sizeArray = [_keepSizeDict allKeys];
//    
//    for (int i = 0; i < sizeArray.count; i++) {
////        NSMutableArray *dataArray = [NSMutableArray array];
//        
////        NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
//        NSDictionary *dataDict = @{@"id":_keepSizeDict[sizeArray[i]]};
////        NSDictionary *dict = @{};
////        NSDictionary *item_attr = @{};
////        [dataArray addObject:dict];
////        [dataArray addObject:item_attr];
//        [attr_id addObject:dataDict];
//    }
 
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        MyLog(@"%lu", (unsigned long)_lastPro.attr.count);
        return _lastPro.attr.count;
    } else {
        return 1;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        HMChangeNumberTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"HMChangeNumberTableViewCell" owner:self options:nil] firstObject];
        cell.delegate = self;
        return cell;
    } else {
        static NSString *identifi = @"HMProductSizeTableViewCell";
        HMProductSizeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifi];
        if (cell == nil) {
            cell = [[HMProductSizeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifi];
        }
//        cell.dataArray = _search.attr[indexPath.row];
        cell.dataDict = _lastPro.attr[indexPath.row];
        cell.delegate = self;
        cell.index = indexPath;
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kHeight;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - HMChangeNumberTableViewCellDelegate
- (void)getNumberOfProduct:(NSString *)textNumber {
    _textNumber = textNumber;
}

#pragma mark - HMProductSizeTableViewCellDelegate
- (void)clickSize:(NSString *)selectString attr_id:(NSString *)attr_id {
    [self.keepSizeDict setObject:selectString forKey:attr_id];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self dismiss];
}


- (NSMutableDictionary *)keepSizeDict {
    if (_keepSizeDict == nil) {
        _keepSizeDict = [NSMutableDictionary dictionary];
    }
    return _keepSizeDict;
}

@end
